/**
 * AI聊天状态管理
 * 支持会话管理、上下文记忆、多用户隔离
 */
import { defineStore } from 'pinia'
import { DeepSeekAPI } from '@/services/deepseekService'

export const useChatStore = defineStore('chat', {
  state: () => ({
    // 会话相关
    sessions: [], // 会话列表
    currentSessionId: null, // 当前选中的会话ID
    currentSession: null, // 当前会话详情
    
    // UI状态
    sidebarCollapsed: false, // 侧边栏是否折叠
    isLoading: false, // 消息发送loading状态
    
    // 系统配置
    systemPrompt: '你是一个专业的AI助手，请为用户提供准确有用的回答。',
    
    // 错误状态
    error: null
  }),

  getters: {
    // 当前会话的消息列表
    currentMessages: (state) => {
      return state.currentSession?.messages || []
    },
    
    // 已回答的消息数量
    answeredCount: (state) => {
      return state.currentMessages.filter(msg => msg.role === 'user').length
    },
    
    // 是否有活跃会话
    hasActiveSession: (state) => {
      return !!state.currentSessionId && !!state.currentSession
    }
  },

  actions: {
    /**
     * 加载用户所有会话
     */
    async loadUserSessions() {
      try {
        const response = await DeepSeekAPI.getUserSessions()
        if (response.success) {
          this.sessions = response.data.sort((a, b) => 
            new Date(b.lastActiveTime) - new Date(a.lastActiveTime)
          )
        }
        return response
      } catch (error) {
        this.error = '加载会话列表失败'
        console.error('Load sessions error:', error)
        return { success: false, message: this.error }
      }
    },

    /**
     * 创建新会话
     */
    async createNewSession(title = '新对话') {
      try {
        const response = await DeepSeekAPI.createSession({
          title,
          systemPrompt: this.systemPrompt
        })
        
        if (response.success) {
          // 添加到会话列表
          this.sessions.unshift(response.data)
          // 自动选择新会话
          await this.selectSession(response.data.sessionId)
        }
        return response
      } catch (error) {
        this.error = '创建会话失败'
        console.error('Create session error:', error)
        return { success: false, message: this.error }
      }
    },

    /**
     * 选择会话
     */
    async selectSession(sessionId) {
      try {
        this.currentSessionId = sessionId
        
        // 获取会话详情
        const response = await DeepSeekAPI.getSessionDetail(sessionId)
        if (response.success) {
          this.currentSession = response.data
        }
        return response
      } catch (error) {
        this.error = '加载会话详情失败'
        console.error('Select session error:', error)
        return { success: false, message: this.error }
      }
    },

    /**
     * 发送消息（上下文对话）
     */
    async sendMessage(message) {
      if (!message?.trim()) return { success: false, message: '消息不能为空' }
      
      this.isLoading = true
      this.error = null
      
      try {
        // 先添加用户消息到本地状态
        this.addMessage('user', message)
        
        // 调用上下文对话API
        const response = await DeepSeekAPI.chatWithContext({
          sessionId: this.currentSessionId,
          message: message.trim()
        })
        
        if (response.success) {
          // 添加AI回复到本地状态
          this.addMessage('assistant', response.data.response)
          
          // 更新会话信息
          if (response.data.session) {
            this.updateSessionInfo(response.data.session)
          }
        } else {
          // 移除失败的用户消息
          this.removeLastMessage()
          this.error = response.message
        }
        
        return response
      } catch (error) {
        this.removeLastMessage() // 移除失败的用户消息
        this.error = '发送消息失败'
        console.error('Send message error:', error)
        return { success: false, message: this.error }
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 重命名会话
     */
    async renameSession(sessionId, newTitle) {
      try {
        const response = await DeepSeekAPI.updateSessionTitle(sessionId, newTitle)
        if (response.success) {
          // 更新本地会话列表
          const sessionIndex = this.sessions.findIndex(s => s.sessionId === sessionId)
          if (sessionIndex !== -1) {
            this.sessions[sessionIndex].title = newTitle
          }
          
          // 如果是当前会话，也更新当前会话信息
          if (this.currentSessionId === sessionId && this.currentSession) {
            this.currentSession.title = newTitle
          }
        }
        return response
      } catch (error) {
        console.error('Rename session error:', error)
        return { success: false, message: '重命名失败' }
      }
    },

    /**
     * 删除会话
     */
    async deleteSession(sessionId) {
      try {
        const response = await DeepSeekAPI.deleteSession(sessionId)
        if (response.success) {
          // 从会话列表中移除
          this.sessions = this.sessions.filter(s => s.sessionId !== sessionId)
          
          // 如果删除的是当前会话，清空当前会话
          if (this.currentSessionId === sessionId) {
            this.currentSessionId = null
            this.currentSession = null
          }
        }
        return response
      } catch (error) {
        console.error('Delete session error:', error)
        return { success: false, message: '删除会话失败' }
      }
    },

    // 辅助方法
    addMessage(role, content) {
      if (!this.currentSession) return
      
      const message = {
        messageId: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        role,
        content,
        timestamp: new Date().toISOString()
      }
      
      this.currentSession.messages.push(message)
    },

    removeLastMessage() {
      if (!this.currentSession?.messages.length) return
      this.currentSession.messages.pop()
    },

    updateSessionInfo(sessionInfo) {
      // 更新会话列表中的会话信息
      const sessionIndex = this.sessions.findIndex(s => s.sessionId === sessionInfo.sessionId)
      if (sessionIndex !== -1) {
        this.sessions[sessionIndex] = { ...this.sessions[sessionIndex], ...sessionInfo }
      }
    },

    // UI控制方法
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    },

    clearError() {
      this.error = null
    }
  }
}) 